import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_sweet_lib/project_demo_page/youpin_pages/page_0.dart';

const img_url =
    'https://c1.mifile.cn/f/i/16/chain/sportearphone-mini//earphonemini-04.jpg';

final bodyColor = Colors.brown[300];

class GoodsDetailsPage extends StatefulWidget {
  final String name;

  const GoodsDetailsPage(this.name);

  @override
  _GoodsDetailsPageState createState() => _GoodsDetailsPageState();
}

class _GoodsDetailsPageState extends State<GoodsDetailsPage> {
  ScrollController _controller = ScrollController();

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      if (_controller.offset >= 250) {
        setState(() {
          _showTitle = true;
        });
      }
      if (_controller.offset == 0.0) {
        setState(() {
          _showTitle = false;
        });
      }
    });
  }

  bool _showTitle = false;

  final _list = ["商品", "详情", "评价"];

  static final _random = Random();

  final List<EvaluateModel> _evaluateModels = List.generate(
      5,
      (i) => EvaluateModel(
          startNum: _random.nextInt(5) + 1,
          name: "随机客户$i",
          color: Colors.blue[100 * ((i + 1) % 9)],
          str: "质量非常好，与描述的完全一致，非常满意，真的很喜欢，完全超出期望值，"
              "发货速度非常快发货速度非常快发货速度非常快发货速度非常快发货速度非常快"
              "发货速度非常快发货速度非常快发货速度非常快发货速度非常快发货速度非常快发货速度非常快发货速度非常快$i"));

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Material(
        color: Colors.white,
        child: Column(
          children: <Widget>[
            Expanded(
                child: CustomScrollView(
              controller: _controller,
              slivers: <Widget>[
                SliverAppBar(
                  centerTitle: true,
                  backgroundColor: Colors.white,
                  elevation: 0.0,
                  leading: IconButton(
                      icon: DetailsIcon(Icons.arrow_back_ios, !_showTitle),
                      onPressed: () => Navigator.of(context).pop()),
                  pinned: true,
                  expandedHeight: 370.0,
                  actions: <Widget>[
                    IconButton(
                        icon: DetailsIcon(
                          Icons.home,
                          !_showTitle,
                        ),
                        onPressed: () {}),
                    IconButton(
                        icon: DetailsIcon(
                          Icons.share,
                          !_showTitle,
                        ),
                        onPressed: () {})
                  ],
                  title: Offstage(
                      offstage: !_showTitle,
                      child: TabBar(
                        tabs: _list
                            .map((name) => Tab(
                                  child: Text(name,
                                      style: TextStyle(
                                          color: Colors.black87,
                                          fontSize: 13.0)),
                                ))
                            .toList(),
                      )),
                  flexibleSpace: FlexibleSpaceBar(
                    background: MySwiper(height: 350.0),
                  ),
                ),
                SliverPadding(
                  padding: EdgeInsets.only(left: 10.0, right: 10.0, top: 10.0),
                  sliver: SliverList(
                    delegate: SliverChildListDelegate(
                      <Widget>[
                        const Text("小米运动蓝牙耳机 青春版",
                            style: TextStyle(
                                fontWeight: FontWeight.w200, fontSize: 18.0)),
                        const SizedBox(height: 5.0),
                        const Text(
                          "蓝牙耳机的质量很好，做工细致，外形美观，戴着舒适，连接稳定，音质棒，性价比高。发货速度快，包装严实！",
                          style: TextStyle(color: Colors.grey, fontSize: 13.0),
                        ),
                        const SizedBox(height: 5.0),
                        Text(
                          "￥99",
                          style: TextStyle(
                              color: Colors.red[700],
                              fontWeight: FontWeight.w500,
                              fontSize: 18.0),
                        ),
                        const SizedBox(height: 5.0),
                        const Divider(height: 1.0),
                        DetailTitleWidget(
                          firstWidget: const Text(
                            "支持:",
                            style: TextStyle(color: Colors.grey),
                          ),
                          secondWidget: Row(
                            children: <Widget>[
                              Icon(Icons.android, color: Colors.blueAccent),
                              const SizedBox(width: 8.0),
                              Text("语音控制的智能设备",
                                  style: TextStyle(fontSize: 13.0)),
                            ],
                          ),
                          onTap: () {
                            _showModalBottomSheet();
                          },
                        ),
                        const Divider(height: 1.0),
                        DetailTitleWidget(
                          onTap: () {_showModalBottomSheet();},
                          firstWidget: const Text("活动:",
                              style: TextStyle(color: Colors.grey)),
                          secondWidget: Row(
                            children: <Widget>[
                              Container(
                                child: Text(
                                  "更多推荐",
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 12.0),
                                ),
                                color: Colors.red[700],
                                padding: EdgeInsets.all(3.0),
                                margin: EdgeInsets.only(right: 3.0),
                              ),
                              Text("智能电视怎么选",
                                  style: TextStyle(
                                      color: Colors.red[700], fontSize: 13.0))
                            ],
                          ),
                        ),
                        const Divider(height: 1.0),
                        const SizedBox(height: 10.0),
                        const Divider(height: 1.0),
                        DetailTitleWidget(
                          firstWidget: const Text("已选:",
                              style: TextStyle(color: Colors.grey)),
                          secondWidget: const Text("请选择颜色 型号 分类",
                              style: TextStyle(fontSize: 13.0)),
                          onTap: () {_showModalBottomSheet();},
                        ),
                        const Divider(height: 1.0),
                        DetailTitleWidget(
                          onTap: () {_showModalBottomSheet();},
                          firstWidget: const Text("送至:",
                              style: TextStyle(color: Colors.grey)),
                          secondWidget: const Text("青岛市市北区",
                              style: TextStyle(fontSize: 13.0)),
                        ),
                        const Divider(height: 1.0),
                        DetailTitleWidget(
                          onTap: () {_showModalBottomSheet();},
                          firstWidget: const Text("说明:",
                              style: TextStyle(color: Colors.grey)),
                          secondWidget: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              ExplainTitleWidget(title: "小米有品甄选精品"),
                              ExplainTitleWidget(title: "由 小米 发货并提供售后"),
                              ExplainTitleWidget(
                                  title: "支持7天无理由退货(请参考商品详情-常见问题)"),
                            ],
                          ),
                        ),
                        const SizedBox(height: 5.0),
                        const Divider(height: 1.0),
                        Padding(
                          padding: EdgeInsets.symmetric(vertical: 5.0),
                          child: EvaluateWidget(_evaluateModels),
                        ),
                        const Divider(height: 1.0),
                        const SizedBox(height: 10.0),
                        const Divider(height: 1.0),
                        RelevantAndTopGoodsWidget(),
                        const SizedBox(height: 10.0),
                      ],
                    ),
                  ),
                ),
              ],
            )),
            const Divider(height: 1.0),
            Container(
                alignment: Alignment.center,
                color: Colors.white,
                height: 60.0,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    BottomButton(
                        icon: Icon(Icons.headset_mic,
                            color: Colors.grey, size: 20.0),
                        title: Text("客服",
                            style:
                                TextStyle(fontSize: 11.0, color: Colors.grey)),
                        onTap: _bottomButtonOnTap),
                    BottomButton(
                        icon: Icon(Icons.favorite_border,
                            color: Colors.grey, size: 20.0),
                        title: Text("收藏",
                            style:
                                TextStyle(fontSize: 11.0, color: Colors.grey)),
                        onTap: _bottomButtonOnTap),
                    BottomButton(
                      icon: Icon(Icons.shopping_cart,
                          color: Colors.grey, size: 20.0),
                      title: Text("购物车",
                          style: const TextStyle(
                              fontSize: 11.0, color: Colors.grey)),
                      onTap: _bottomCartButtonOnTap,
                      count: 6,
                    ),
                    FlatButton(
                      color: Colors.red[800],
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20.0)),
                      child:
                          Text("立即购买", style: TextStyle(color: Colors.white)),
                      onPressed: () {},
                    ),
                    FlatButton(
                      color: bodyColor,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20.0)),
                      child:
                          Text("加入购物车", style: TextStyle(color: Colors.white)),
                      onPressed: () {},
                    ),
                  ],
                )),
          ],
        ),
      ),
    );
  }

  void _bottomButtonOnTap() {}

  void _bottomCartButtonOnTap() {}

  void _showModalBottomSheet() {
    var height = MediaQuery.of(context).size.height * (0.8);
    showModalBottomSheet<Null>(
        context: context,
        builder: (BuildContext context) {
          return SingleChildScrollView(
            child: Container(
                height: height,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.all(8.0),
                      child:
                          const Text("促销活动", style: TextStyle(fontSize: 18.0)),
                    ),
                    const Divider(height: 1.0),
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Container(
                        margin: EdgeInsets.all(10.0),
                        height: 23.0,
                        width: 60.0,
                        alignment: Alignment.center,
                        padding: EdgeInsets.all(3.0),
                        child: Text("更多推荐",
                            style:
                                TextStyle(fontSize: 13.0, color: Colors.white)),
                        decoration: BoxDecoration(
                          color: Colors.red[700],
                          borderRadius: BorderRadius.circular(5.0),
                        ),
                      ),
                    ),
                    Align(
                        child: Padding(
                            padding: EdgeInsets.only(left: 10.0),
                            child: const Text("智能电视怎么选",
                                style: TextStyle(fontSize: 14.0))),
                        alignment: Alignment.centerLeft),
                  ],
                )),
          );
        });
  }
}

class RelevantAndTopGoodsWidget extends StatefulWidget {
  @override
  _RelevantAndTopGoodsWidgetState createState() =>
      _RelevantAndTopGoodsWidgetState();
}

class _RelevantAndTopGoodsWidgetState extends State<RelevantAndTopGoodsWidget> {
  List<RelevantTitleModel> _models = [
    RelevantTitleModel(
        title: "相关推荐",
        goods: List.generate(5, (i) => "相关商品$i"),
        showFlag: true),
    RelevantTitleModel(title: "排行版", goods: List.generate(5, (i) => "热门商品$i")),
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: _models
              .map((model) => RelevantTitleWidget(
                  title: model.title,
                  showFlag: model.showFlag,
                  onTap: () => _onTap(model)))
              .toList(),
        ),
        Container(
          padding: EdgeInsets.symmetric(vertical: 10.0),
          child: ListView(
            scrollDirection: Axis.horizontal,
            itemExtent: 100.0,
            children: _models.firstWhere((i) => i.showFlag).goods.map((good) {
              return Container(
                  alignment: Alignment.bottomCenter,
                  width: 80.0,
                  height: 80.0,
                  decoration: BoxDecoration(
                    color: Colors.grey[300],
                    borderRadius: BorderRadius.circular(5.0),
                  ),
                  child: Text(good),
                  margin: EdgeInsets.symmetric(horizontal: 3.0));
            }).toList(),
          ),
          height: 100.0,
        ),
        const Divider(height: 1.0),
        Container(
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(vertical: 10.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              FlutterLogo(
                size: 45.0,
                colors: Colors.orange,
              ),
              const SizedBox(width: 10.0),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text("小米自营产品",
                      style: TextStyle(
                          fontWeight: FontWeight.bold, fontSize: 16.0)),
                  Text(
                    "为发烧而生",
                    style: TextStyle(color: Colors.grey),
                  )
                ],
              )
            ],
          ),
        ),
      ],
    );
  }

  void _onTap(RelevantTitleModel model) {
    final _newModels = _models.map((m) {
      if (m.title == model.title) {
        return RelevantTitleModel(
            title: m.title, showFlag: true, goods: m.goods);
      }
      return RelevantTitleModel(
          title: m.title, showFlag: false, goods: m.goods);
    }).toList();
    setState(() {
      _models = _newModels;
    });
  }
}

class RelevantTitleWidget extends StatelessWidget {
  final String title;
  final bool showFlag;
  final VoidCallback onTap;

  RelevantTitleWidget({this.title, this.showFlag = false, this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
        child: Text(title,
            style: TextStyle(color: showFlag ? bodyColor : Colors.black)),
        margin: EdgeInsets.all(5.0),
        padding: EdgeInsets.symmetric(vertical: 5.0),
        decoration: UnderlineTabIndicator(
          borderSide: BorderSide(
              color: showFlag ? bodyColor : Colors.white,
              style: BorderStyle.solid,
              width: 3.0),
        ),
      ),
      onTap: onTap,
    );
  }
}

class RelevantTitleModel {
  final String title;
  final bool showFlag;
  final List<String> goods;

  const RelevantTitleModel({this.title, this.showFlag = false, this.goods});
}

class EvaluateModel {
  final String name;
  final Color color;
  final int startNum;
  final String str;

  const EvaluateModel({this.name, this.color, this.startNum, this.str});
}

class EvaluateWidget extends StatelessWidget {
  final List<EvaluateModel> models;

  EvaluateWidget(this.models);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 12.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text("用户评价(1753)",
                  style: TextStyle(fontSize: 13.0, color: Colors.black)),
              Row(
                children: <Widget>[
                  Text("97%满意",
                      style: TextStyle(fontSize: 13.0, color: bodyColor)),
                  Icon(Icons.arrow_forward_ios, color: bodyColor),
                ],
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
              )
            ],
          ),
        ),
        Container(
          child: ListView(
              children:
                  models.map((model) => EvaluateItemWidget(model)).toList(),
              scrollDirection: Axis.horizontal,
              itemExtent: 300.0),
          height: 140.0,
        ),
        GestureDetector(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text("查看更多", style: TextStyle(color: bodyColor)),
                  Icon(Icons.arrow_right, color: bodyColor)
                ],
              ),
            ),
            onTap: () {}),
      ],
    );
  }
}

class EvaluateItemWidget extends StatelessWidget {
  final EvaluateModel model;

  EvaluateItemWidget(this.model);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey[200],
        borderRadius: BorderRadius.circular(8.0),
      ),
      alignment: Alignment.center,
      margin: EdgeInsets.symmetric(horizontal: 5.0),
      padding: EdgeInsets.all(10.0),
      width: 300.0,
      height: 140.0,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(right: 8.0),
                child: CircleAvatar(
                  backgroundColor: model.color,
                  radius: 18.0,
                ),
              ),
              Expanded(
                child: Text(model.name,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontSize: 13.0)),
              ),
              StarListWidget(model.startNum),
            ],
          ),
          Text(model.str,
              softWrap: true, overflow: TextOverflow.ellipsis, maxLines: 3),
        ],
      ),
    );
  }
}

class StarListWidget extends StatelessWidget {
  final int startNum;

  StarListWidget(this.startNum);

  @override
  Widget build(BuildContext context) {
    final iconSize = Theme.of(context).iconTheme.size;
    return Container(
      height: 30.0,
      width: 100.0,
      child: Stack(
        children: <Widget>[
          ListView(
              children: List.generate(
                  5,
                  (i) => Icon(Icons.star_border,
                      size: 13.0, color: Colors.orangeAccent)),
              scrollDirection: Axis.horizontal,
              itemExtent: iconSize),
          ListView(
              children: List.generate(
                  startNum,
                  (i) =>
                      Icon(Icons.star, size: 13.0, color: Colors.orangeAccent)),
              scrollDirection: Axis.horizontal,
              itemExtent: iconSize),
        ],
      ),
    );
  }
}

class BottomButton extends StatelessWidget {
  final Icon icon;
  final Widget title;
  final int count;
  final VoidCallback onTap;

  const BottomButton({this.icon, this.title, this.onTap, this.count});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Stack(
            children: <Widget>[
              icon,
              Positioned(
                child: Offstage(
                    offstage: count == null,
                    child: CircleAvatar(
                        radius: 6.0,
                        backgroundColor: Colors.red[500],
                        child: Text(
                          count.toString(),
                          style: TextStyle(fontSize: 8.0, color: Colors.white),
                        ))),
                top: 0,
                right: 0,
              ),
            ],
          ),
          title
        ],
      ),
      onTap: onTap,
    );
  }
}

class ExplainTitleWidget extends StatelessWidget {
  final String title;

  ExplainTitleWidget({this.title});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 3.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Icon(Icons.beenhere, color: Colors.grey, size: 13.0),
          SizedBox(width: 3.0),
          SizedBox(
            width: 250.0,
            child: Text(
              title,
              style: TextStyle(fontSize: 13.0),
              softWrap: true,
            ),
          )
        ],
      ),
    );
  }
}

class DetailTitleWidget extends StatelessWidget {
  final Widget firstWidget;
  final Widget secondWidget;
  final VoidCallback onTap;

  DetailTitleWidget({this.firstWidget, this.secondWidget, this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 5.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Row(children: <Widget>[
              firstWidget,
              const SizedBox(width: 8.0),
              secondWidget,
            ], crossAxisAlignment: CrossAxisAlignment.start),
            Icon(Icons.chevron_right, color: Colors.grey),
          ],
        ),
      ),
      onTap: onTap,
    );
  }
}

class DetailsIcon extends StatelessWidget {
  final IconData iconData;
  bool showBackground;

  DetailsIcon(this.iconData, this.showBackground);

  @override
  Widget build(BuildContext context) {
    return CircleAvatar(
      child: Icon(iconData, color: showBackground ? Colors.white : Colors.grey),
      backgroundColor: showBackground ? Colors.grey[500] : Colors.white,
    );
  }
}
